﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using KBManagement.DAL;
using KBManagement.BIZ;
using KBManagement.OrderProcess;
using System.IO;
using System.Globalization;
using KBManagement.Library;
namespace KBManagement
{
    public partial class SellingPanel : Form, CustomerObserver
    {
        private ProductsState ps;
        private FoodManagement foodManagement;
        private FoodFacade foodFacade;
        private ProductFacade productFacade;
        private CategoryFacade categoryFacade;
        private FoodCategoryFacade foodCategoryFacade;
        private InputProcess proces;
        private StoreTempFacade storeTempFacade;
        private IQueryable oDetailOrder;
        private Purchase_Order pOrder;
        private Boolean finish = false;
        private PrintOrder printOrder;
        String total = "0";
        Admin admin;
        public SellingPanel(Admin admin)
        {
            this.admin = admin;
            storeTempFacade = new StoreTempFacade();
            proces = new InputProcess(this);
            Utils.CreateInstance().AddInforObserver(proces);
            Utils.CreateInstance().AddCustomerObserver(this);
            foodCategoryFacade = new FoodCategoryFacade();
            foodFacade = new FoodFacade();
            productFacade = new ProductFacade();
            categoryFacade = new CategoryFacade();
            InitializeComponent();
            SelectFood();
            gvFoods.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            gvFoods.MultiSelect = false;
            gvUsedFoods.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            gvUsedFoods.MultiSelect = false;
            SelectFoodCategory();
            SetProduct();
            lbl.Text = "Xin chào : " + admin.UserName + "   ";
        }

        private void setFoodHeader()
        {
            gvFoods.Columns[0].HeaderText = "Mã";
            gvFoods.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            gvFoods.Columns[1].HeaderText = "Tên";
            gvFoods.Columns[2].HeaderText = "Giá";


        }

        void foodManagement_Disposed(object sender, EventArgs e)
        {
            foodManagement = null;
        }

        private void SelectFood()
        {
            gvFoods.DataSource = foodFacade.Select();
            setFoodHeader();
        }
        private void SetProduct()
        {
            if (checkFinish()) { return; }
            Category[] categorys = categoryFacade.SelectEntities();

            ListView lv;

            ImageList imglist = new ImageList();

            imglist.Images.Add("images1", global::KBManagement.Properties.Resources.images);
            imglist.Images.Add("images", global:: KBManagement.Properties.Resources.images1);
            imglist.Images.Add("KAR", global:: KBManagement.Properties.Resources.KAR);
            imglist.Images.Add("KAR1", global:: KBManagement.Properties.Resources.KAR1);
            imglist.ImageSize = new Size(80, 80);
            imglist.ColorDepth = ColorDepth.Depth32Bit;

            for (int i = 0; i < categorys.Length; i++)
            {
                TabPage tp = new TabPage(categorys[i].Name);
                lv = new ListView();

                lv.Name = categorys[i].ID;
                lv.MultiSelect = false;
                lv.View = View.LargeIcon;
                lv.LargeImageList = imglist;
                lv.MouseClick += new MouseEventHandler(lv_MouseClick);
                Product[] products = productFacade.FindMany(categorys[i].ID);
                for (int j = 0; j < products.Length; j++)
                {

                    ps = ProductsState.GetProductsState();
                    ps.AddProduct(products[j]);
                    var proItem = ps.GetItem(products[j]);
                    string image = "";
                    if (proItem.Status)
                    {
                        image = products[j].ImageUsePath;
                    }
                    else
                    {
                        image = products[j].ImageNotUsePath;
                    }
                    ListViewItem item = new ListViewItem(products[j].Name, image);
                    item.Name = products[j].Name;
                    lv.Items.Add(item);


                }
                lv.Dock = DockStyle.Fill;
                tp.Controls.Add(lv);
                tabControl1.Controls.Add(tp);
            }
        }
        ListViewItem selectedItem;
        void lv_MouseClick(object sender, MouseEventArgs e)
        {
            if (checkFinish()) { return; }
            ListView l = sender as ListView;
            selectedItem = l.SelectedItems[0];
            Product p = productFacade.FindByName(selectedItem.Text);
            ProductItem item = ps.GetItem(p);

            ShowAllInfor(item);
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                if (item.Status)
                {
                    mnEnd.Enabled = true;
                    mnStart.Enabled = false;
                    mnChange.Enabled = true;

                    mnChange.DropDownItems.Clear();
                    mnChange.DropDownItems.AddRange(GetDropDownItem(p));

                }
                else
                {
                    mnChange.Enabled = false;
                    mnStart.Enabled = true;
                    mnEnd.Enabled = false;


                }
                menuRightMouse.Show(l, e.Location);


            }

        }
        private ToolStripMenuItem[] GetDropDownItem(Product p)
        {
            var mn = new List<ToolStripMenuItem>();
            foreach (var item in ps.GetItemsByCategoryAndStatus(p, false))
            {
                ToolStripMenuItem it = new ToolStripMenuItem(item.product.Name);
                it.Name = item.product.Name;
                it.Click += new EventHandler(SubMenuItem_Click);
                mn.Add(it);
            }
            return mn.ToArray();
        }

        void SubMenuItem_Click(object sender, EventArgs e)
        {
            if (checkFinish()) { return; }
            var item = sender as ToolStripMenuItem;
            ps.ChangeProduct(selectedItem.Text, item.Name);
            Product p = productFacade.FindByName(selectedItem.Text);
            Product p2 = productFacade.FindByName(item.Name);
            selectedItem.ImageKey = p.ImageNotUsePath;
            selectedItem.ListView.Items.Find(item.Name, false)[0].ImageKey = p2.ImageUsePath;
            txtStartTime.Text = "";

        }
        private void ShowAllInfor(ProductItem item)
        {

            lblProductName.Text = item.product.Name;
            if (item.purchaseOrder != null)
            {
                ShowInfor(item);
            }
            else
            {
                txtStartTime.Text = "";
                txtEndTime.Text = "";
                txtUsedTime.Text = "";
                gvUsedFoods.DataSource = null;
                txtPrice.Text = String.Format("{0:0,0} VNĐ", item.product.Price);
                lblTotal.Text = "VNĐ";
            }
        }

        private void ShowInfor(ProductItem item)
        {
            if (item.purchaseOrder != null)
            {
                DateTime d = item.purchaseOrder.StartTime.Value;
                txtStartTime.Text = d.ToString("t", CultureInfo.CreateSpecificCulture("es-ES"));
                txtSale.Text = item.purchaseOrder.Sale_Rate.ToString();
                txtPrice.Text = String.Format("{0:0,0} VNĐ", item.product.Price);

                if (item.purchaseOrder.EndTime.HasValue)
                {
                    txtEndTime.Text = item.purchaseOrder.EndTime.Value.ToString("t", CultureInfo.CreateSpecificCulture("es-ES"));
                }
                if (item.purchaseOrder.Customer != null)
                {
                    txtCustomer.Text = item.purchaseOrder.Customer.FullName;
                    txtSale.Text = item.purchaseOrder.Sale_Rate.ToString();
                }
                else
                {
                    txtCustomer.Text = "";
                    txtSale.Text = "0";
                }
                lblTotal.Text = String.Format("{0:0,0} VNĐ", item.purchaseOrder.Total_Amount.Value);
                total = item.purchaseOrder.Total_Amount.Value.ToString();
                gvUsedFoods.DataSource = item.GetServices();


                gvUsedFoods.Columns[0].HeaderText = "Tên";
                gvUsedFoods.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                gvUsedFoods.Columns[1].HeaderText = "SốLượng";
                gvUsedFoods.Columns[2].HeaderText = "TổngTiền";
            }



        }
        private void SelectFoodCategory()
        {
            pnFoodCategory.Controls.Clear();
            FoodCaterory[] fc = foodCategoryFacade.SelectEntities();
            Button btn;

            for (int i = 0; i < fc.Length; i++)
            {
                btn = new Button();
                btn.Name = fc[i].ID.ToString();
                btn.Text = fc[i].Name;
                btn.Click += new EventHandler(btn_Click);
                // btn.Image = Properties.Resources.star;
                btn.Size = new Size(80, 40);
                btn.BackColor = Color.Black;
                btn.ForeColor = Color.White;
                btn.Font = new System.Drawing.Font("Microsoft Sans Serif", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel, ((byte)(0)));
                pnFoodCategory.Controls.Add(btn);
            }

        }

        void btn_Click(object sender, EventArgs e)
        {
            if (checkFinish()) { return; }
            Button b = sender as Button;
            gvFoods.DataSource = foodFacade.FindMany(Convert.ToInt16(b.Name));
        }
        void button_Click(object sender, EventArgs e)
        {
            if (checkFinish()) { return; }
            MessageBox.Show(((Button)sender).Name);
        }

        private void btnService_Click(object sender, EventArgs e)
        {
            if (checkFinish()) { return; }
            if (foodManagement == null)
            {
                foodManagement = new FoodManagement();
                foodManagement.Disposed += new EventHandler(foodManagement_Disposed);
                foodManagement.Show();
            }

        }
        ProductItem item;
        private void StartOrStop(bool mode)
        {
            item = ps.GetItem(productFacade.FindByName(selectedItem.Text));
            if (mode)
            {
                item.Start();
                selectedItem.ImageKey = item.product.ImageUsePath;
                ShowInfor(item);
            }
            else
            {
                
                oDetailOrder = item.GetOrderDetail();
                pOrder = Utils.CreateInstance().GetDBContext().Purchase_Orders.SingleOrDefault(x => x.Product.Name == selectedItem.Text && x.Status == false);
                item.CalculateAmount();
                selectedItem.ImageKey = item.product.ImageNotUsePath;
                txtUsedTime.Text = item.UsedTime;
                ShowInfor(item);
            }

        }

        private void mnStart_Click(object sender, EventArgs e)
        {

            StartOrStop(true);
        }

        private void mnEnd_Click(object sender, EventArgs e)
        {
            CheckOut.Enabled = true;
            btnFind.Enabled = true;
            StartOrStop(false);
            finish = true;
        }

        private void mnAddFood_Click(object sender, EventArgs e)
        {
            if (checkFinish()) { return; }
            ServicesProcess(true);
        }

        private void mnDelete_Click(object sender, EventArgs e)
        {
            if (checkFinish()) { return; }
            ServicesProcess(false);
        }

        private void ServicesProcess(bool addordelete)
        {
            if (selectedItem == null)
            {
                MessageBox.Show("Chưa chọn bàn hoặc phòng");
            }
            else
            {
                Product p = productFacade.FindByName(selectedItem.Text);
                ProductItem item = ps.GetItem(p);
                if (item.Status)
                {


                    InputBox b = new InputBox();
                    b.observer = proces;
                    b.ShowDialog();
                    int quantity = proces.Quantity;

                    if (addordelete)
                    {
                        if (gvFoods.SelectedRows.Count > 0)
                        {
                            Food f = foodFacade.Find(gvFoods.SelectedRows[0].Cells[0].Value.ToString());
                            if (storeTempFacade.AddService(f, quantity))
                            {
                                item.AddService(f, quantity);
                            }
                            else
                            {
                                MessageBox.Show("Một số thành phần trong kho không đủ xin kiểm tra lại");
                            }
                        }
                    }
                    else
                    {
                        if (gvUsedFoods.SelectedRows.Count > 0)
                        {
                            Food f = foodFacade.FindByName(gvUsedFoods.SelectedRows[0].Cells[0].Value.ToString());

                            if (quantity <= Convert.ToInt32(gvUsedFoods.SelectedRows[0].Cells[1].Value))
                            {
                                item.RemoveServices(gvUsedFoods.SelectedRows[0].Cells[0].Value.ToString(), quantity);
                                storeTempFacade.DeleteService(f, quantity);
                            }
                        }
                    }
                    ShowInfor(item);
                }
            }
        }
        private void SetCustomerInfor(Customer customer)
        {
            ProductItem item = ps.GetItem(productFacade.FindByName(selectedItem.Text));

            item.SetCustomer(customer);
            ShowInfor(item);
        }

        private class InputProcess : IObserver, InforObserver
        {
            public int Quantity { get; set; }
            SellingPanel s;

            public InputProcess(SellingPanel s)
            {
                this.s = s;
                Quantity = 1;
            }

            public void UpdateQuantity(int Quantity)
            {
                this.Quantity = Quantity;
            }
            public void UpdateCustomer(Customer customer)
            {
                s.SetCustomerInfor(customer);
            }

            public void Update()
            {

                s.SelectFood();
                s.SelectFoodCategory();
                //s.SetProduct();
            }
        }

        private void btnFind_Click(object sender, EventArgs e)
        {
            FindCustomer find = new FindCustomer();
            find.ShowDialog();

        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            if (checkFinish()) { return; }
            new EmployeeManagement().Show();
        }

        private void btnStock_Click(object sender, EventArgs e)
        {
            if (checkFinish()) { return; }
            new WareHouse().Show();
        }

        private void btnLogout_Click(object sender, EventArgs e)
        {
            if (checkFinish()) { return; }
            ConfirmLogOut confirm = new ConfirmLogOut();
            if (confirm.ShowDialog() == DialogResult.OK)
            {
                Application.Exit();
            }
        }

        private void btnCustomer_Click(object sender, EventArgs e)
        {
            if (checkFinish()) { return; }
            new ManageCustomer().Show();
        }

        private void SellingPanel_FormClosed(object sender, FormClosedEventArgs e)
        {
                        
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            if (checkFinish()) { return; }
            new ExtraFees().Show();
        }

        public void UpdateCustomer(Customer customer)
        {
            txtCustomer.Text = customer.FullName;
        }

        public Boolean checkFinish()
        {
            if (finish)
            {
                MessageBox.Show("Hóa đơn hiện tại chưa được thanh toán");
                return true;
            }
            return false;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            new PrintOrder(oDetailOrder, pOrder, DateTime.Now, txtCustomer.Text, total).Show();
            item.Stop();
            txtStartTime.Text = "";
            txtEndTime.Text = "";
            txtUsedTime.Text = "";
            gvUsedFoods.DataSource = null;
            txtPrice.Text = String.Format("{0:0,0} VNĐ",0);
            lblTotal.Text = "VNĐ";
            item.purchaseOrder = null;
            CheckOut.Enabled = false;
            btnFind.Enabled = false;
            finish = false;
        }

        


        private void SellingPanel_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!checkFinish())
            {
                ConfirmLogOut confirm = new ConfirmLogOut();
                if (confirm.ShowDialog() == DialogResult.OK)
                {
                    Environment.Exit(0);
                }
                else
                {
                    e.Cancel = true;
                }
            }
            else
            {
                e.Cancel = true;
            }
        }
    }
}
